/* eslint-disable react-refresh/only-export-components */
import MyNavBar from '../../components/navbar'
import { Button, Toast } from 'antd-mobile'
import { AddCircleOutline } from 'antd-mobile-icons'
import PsgCardList from './components/PsgCardList'
import { getPsgListApi } from '../../api/psg'
import styles from './css/psg.module.css'
import { useLoaderData, useNavigate, useSearchParams } from 'react-router-dom'
import { useRef } from 'react'
import { useDispatch } from 'react-redux'
import { addPsgArr } from '../../store/slice/orderSlice'

function PsgList() {
  const { list } = useLoaderData()
  const [sp] = useSearchParams()
  // 定义一个 ref，用来存储选择的乘车人的数组
  const psgRef = useRef([])
  const dispatch = useDispatch()
  const nav = useNavigate()

  const onChange = (arr) => {
    psgRef.current = arr
  }

  // 点击提交按钮，把选择的乘客信息，存入仓库中
  const postPsg = () => {
    if (psgRef.current.length === 0) return Toast.show('请选择乘车人！')
    // 把 psgRef.current 这个数组，提交到仓库中进行保存
    dispatch(addPsgArr(psgRef.current))
    nav(-1)
  }

  return (
    <div className={styles.box}>
      {/* 顶部导航 */}
      <MyNavBar title="乘客列表" />

      {/* 新增乘客的 Button */}
      <Button
        block
        color="primary"
        fill="outline"
        style={{ backgroundColor: '#fff' }}
        onClick={() => nav('/psg-add')}
      >
        <AddCircleOutline />
        <span style={{ marginLeft: '5px' }}>新增乘客</span>
      </Button>

      {/* 乘客的列表 */}
      <PsgCardList
        list={list}
        onChange={onChange}
      />

      {/* 提交的按钮 */}
      {sp.get('mode') === 'choose' && (
        <div className={styles.btnFooter}>
          <Button
            block
            color="primary"
            shape="rounded"
            onClick={postPsg}
          >
            提交
          </Button>
        </div>
      )}
    </div>
  )
}

export default PsgList

export const loader = async () => {
  const { data: res } = await getPsgListApi()
  console.log(res)
  return { list: res }
}
